package roboticsfmw.sample;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import roboticsfmw.core.HardwareException;
import roboticsfmw.core.HardwareProxy;


public class UserIOHardwareProxy implements HardwareProxy {

	private JFrame myFrame;
	public String command;
	private JButton cmdButton;
	private JTextField cmdField;
	private JTextArea logArea;
	
	@Override
	public void init() throws HardwareException {
		
		myFrame = new JFrame("Sample Robot IO User Interface");
		myFrame.setSize(400, 300);
		myFrame.setLayout(new BorderLayout());
		
		logArea = new JTextArea(10,60);
		logArea.setEditable(false);
		
		myFrame.add(logArea,BorderLayout.CENTER);
		
		Container cmdCnt = new Container();
		cmdCnt.setLayout(new FlowLayout(FlowLayout.LEFT));
		myFrame.add(cmdCnt,BorderLayout.SOUTH);
		
		JLabel l1 = new JLabel("Command>");
		cmdCnt.add(l1);
		
		cmdField = new JTextField(20);
		cmdField.addKeyListener(new KeyListener(){
			@Override
			public void keyPressed(KeyEvent e) {
			}

			@Override
			public void keyReleased(KeyEvent e) {
			}

			@Override
			public void keyTyped(KeyEvent e) {
				if (e.getKeyChar() == '\n') {
					command = cmdField.getText();
					cmdField.setText("");
					cmdField.requestFocus();
				}
			}
		});
		cmdCnt.add(cmdField);
		
		cmdButton = new JButton("Send");
		cmdButton.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent arg0) {
				command = cmdField.getText();
				cmdField.setText("");
				cmdField.requestFocus();
			}
		});
		cmdCnt.add(cmdButton);
		
		myFrame.setVisible(true);
		myFrame.pack();
		
	}
	
	@Override
	public void shutdown() throws HardwareException {
		myFrame.dispose();
	}

	public void sendCommand(String msg){
		this.logArea.append("["+new Date()+"] "+msg+"\n");
	}
	
	
}
